/*
 * Copyright 2001-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package code.buildit.plugin.adapter;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;

public class PsiClassAdapter {
    private Project project;

    public PsiClassAdapter(Project project) {
        this.project = project;
    }

    public PsiClass getSelectedClass() {
        PsiFile psiFile = getCurrentFile();
        if (!isAJavaClass(psiFile))
            return null;

        PsiJavaFile javaFile = (PsiJavaFile) psiFile;
        return javaFile.getClasses()[0];
    }

    public boolean isAClass() {
        PsiClass aClass = getSelectedClass();
        return aClass != null && !aClass.isInterface();
    }

    public PsiClass findPsiClassByName(Project project, PsiManager psiManager, String canonicalText) {
        return psiManager.findClass(canonicalText, GlobalSearchScope.projectScope(project));
    }

    private PsiFile getCurrentFile() {
        if (project == null)
            return null;

        Editor selectedEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (selectedEditor == null)
            return null;

        return PsiDocumentManager.getInstance(project).getPsiFile(selectedEditor.getDocument());
    }

    private boolean isAJavaClass(PsiFile psiFile) {
        return psiFile != null && psiFile instanceof PsiJavaFile;
    }
}
